package com.online.edu.course.utils;

import com.github.tobato.fastdfs.domain.fdfs.MetaData;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

@Component
public class FileStoreUtil {

    private final static String GROUP = "group1";

    @Autowired
    protected FastFileStorageClient storageClient;

    /**
     * 上传文件到服务器,不携带信息
     * @param input 文件输入流
     * @param fileExtName  文件扩展名
     * @return 返回服务器的相对路径
     * @throws IOException 读取文件流失败
     */
    public String uploadFile(InputStream input,String fileExtName) throws IOException {
        StorePath storePath = storageClient.uploadFile(GROUP, input, input.available(), fileExtName);
        return storePath.getFullPath();
    }

    /**
     * 上传文件到服务器，并携带文件信息
     * @param input 文件输入流
     * @param fileExtName  文件扩展名
     * @param metaData 文件携带的信息
     * @return
     */
    public String uploadFile(InputStream input, String fileExtName, Map<String,String> metaData) throws IOException {
        StorePath storePath = storageClient.uploadFile(input, input.available(), fileExtName, this.createMetaData(metaData));
        return storePath.getFullPath();
    }

    /**
     * 获取文件信息
     * @param filePath 文件的相对路径(不带域名)
     * @return 信息标签
     */
    public Map<String,String> getMetaData(String filePath){
        Map<String,String> metaData = new HashMap<>();
        Set<MetaData> metadata = storageClient.getMetadata(GROUP, filePath.substring(GROUP.length() + 1));
        for (MetaData item : metadata) {
            metaData.put(item.getName(),item.getValue());
        }
        return metaData;
    }

    /**
     * 设置MetaData
     * @param metaData 信息标签
     * @return 返回MetaData
     */
    private Set<MetaData> createMetaData(Map<String,String> metaData){
        Set<MetaData> metaDataSet = new HashSet<>();;
        for (String s : metaData.keySet()) {
            metaDataSet.add(new MetaData(s,metaData.get(s)));
        }
        return metaDataSet;
    }

}
